<?php


namespace app\miniapp\controller\v1;

use app\common\lib\exception\ApiException;
use app\common\lib\Util;
use think\Cache;
use think\Controller;
use think\Log;
use think\Request;

class CustomerService extends Controller
{

    protected $token = 'zhunle_astro';//验证微信请求的token
    protected $aes_key = 'aj7aGMjGtWr8sUg4ohLSdb0KNxebtfDzJ2BgkD5X7bP';//自动回复解密微信请求数据的密钥
    protected $app_id = 'wx13aa45fb16ed9635';//appid
    protected $app_secret = '7c09934c7ec7a45433410337ff935b25';//appsecret

    /**
     * 自动回复接口
     * @return \think\response\Json
     */
    public function autoReply()
    {
        // 是否为 GET 请求
        if (Request::instance()->isGet())
        {
//            Log::write('微信客服get请求数据：' . var_export(\request()->param(), true), 'log', true);
            $this->valid();
        }
        // 是否为 POST 请求
        if (Request::instance()->isPost())
        {
//            Log::write('微信客服post请求数据：' . var_export(\request()->param(), true), 'log', true);
            $res = $this->responseMsg();
            return show(config('code.success'), '获取成功', $res);
        }
    }

    /**
     * 检验是否为微信请求
     */
    public function valid()
    {
        $echoStr = input('echostr', '');
        if ($this->checkSignature())
        {
            header('content-type:text');
            echo $echoStr;
            exit;
        }
        echo $echoStr . '+++' . $this->token;
        exit;
    }

    /**
     * 检验是否是微信的请求
     * @link https://developers.weixin.qq.com/miniprogram/dev/framework/server-ability/message-push.html (验证微信消息推送)
     */
    private function checkSignature()
    {
        $signature = input('signature', '');
        $timestamp = input('timestamp', '');
        $nonce = input('nonce', '');

        $token = $this->token;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        return $tmpStr == $signature;
    }

    /**
     * 客服自动回复
     * @link https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/customer-message/customerServiceMessage.send.html  （微信客小程序客服自动回复）
     */
    public function responseMsg()
    {
//        $postArr = array(
//            'signature' => '29449ef5769dade5c4d14aff7a33d33e93767aa6',
//            'timestamp' => '1591258088',
//            'nonce' => '667945276',
//            'openid' => 'o09Kv4uus7M9XlJgV8rJEKIGV_L0',
//            'encrypt_type' => 'aes',
//            'msg_signature' => '56dc0ca968b556c50920fe9c2dd4a22fccf6f9fd',
//            'ToUserName' => 'gh_0fad5a51c053',
//            'FromUserName' => 'o09Kv4uus7M9XlJgV8rJEKIGV_L0',
//            'CreateTime' => 1591258087,
//            'MsgType' => 'text',
//            'Content' => '1',
//            'MsgId' => 22781339013161815,
//            'Encrypt' => 'az5lbS8tpFzhHPvqKi5HCsR+nZg2ur4z1+ozS6BN0N5eclQmKpIq6Ax+gpcs4rgjUtagnIUyvWGZs1bk3NfOWu0wqmZvgkg0q83cqDtL4U79TLr+rFshEkQlNAsf5GwZ/J/wAG7XkLK9NoBL4mypOVQZdDEUPNYX7MYkVmkrriCnlREBdiJRi9HK6PX8hG/MLEneTUPPAl9C7cfnu3L3TDN9r3J3ZCWjYPt0WCJXZFYniJVqmIMo8hWbJzShvV//XYuPufoFxqdwGfgEGXmOOOVlUcEus0JLPesFWaCG+V0=',
//            'ver' => 'v1',
//        );

        $postArr = \request()->param();
        if (!empty($postArr))
        {
            $type = 1;
            //文本消息
            if (!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text')
            {
//                $fromUsername = $postArr['FromUserName'];   //发送者openid
//                $toUserName = $postArr['ToUserName'];       //小程序id
                if ($postArr['Content'] == '1')//如用户出触发关键词，则发送图文跳转app下载页面
                {
                    $type = 3;
                }
            }

            //图文消息
//            if (!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image')
//            {
//                $fromUsername = $postArr['FromUserName'];   //发送者openid
//                $toUserName = $postArr['ToUserName'];       //小程序id
//            }

            $res = $this->replyMsg($postArr['FromUserName'], $type);
            echo $res;
            exit;

            //客服自动回复
//            if ($postArr['MsgType'] == 'event' && $postArr['Event'] == 'user_enter_tempsession')
//            {
//
//            }
        }
    }

    /**
     * 自动回复
     * @param string $fromUsername 发送者openid
     * @param int $type 消息类型，1=>文本为text，2=>图片为image，3=>图文为link，4=>小程序为miniprogrampage
     * @return bool|string
     */
    public function replyMsg($fromUsername, $type)
    {
        //进入客服动作
        switch ($type)
        {
            case 1://文本
                $content = '您好，有什么能帮助你?';
                $data = [
                    'touser' => $fromUsername,
                    'msgtype' => 'text',
                    'text' => [
                        'content' => $content
                    ]
                ];
                //发送文本消息时，支持插入跳小程序的文字链
                //文本内容<a href="http://www.qq.com" data-miniprogram-appid="appid" data-miniprogram-path="pages/index/index">点击跳小程序</a>
                break;
            case 2://图片
                $data = [
                    'touser' => $fromUsername,
                    'msgtype' => 'image',
                    'image' => [
                        'media_id' => ''
                    ]
                ];
                break;
            case 3://图文（点击跳转到图文消息页面）
                $data = [
                    'touser' => $fromUsername,
                    'msgtype' => 'link',
                    'link' => [
                        'title' => '点击下载准了APP',
                        'description' => '准了app，您的运势好伴侣',
                        'url' => 'https://www.zhunleapp.com/',//小程序的页面路径，跟app.json对齐，支持参数，比如pages/index/index?foo=bar
                        'thumb_url' => 'https://t9.baidu.com/it/u=3363001160,1163944807&fm=79&app=86&size=h300&n=0&g=4n&f=jpeg?sec=1591862371&t=694ebee837ba8b17a863f11573c362fe'//缩略图/小程序卡片图片的媒体ID，小程序卡片图片建议大小为520*416
                    ]
                ];
                break;
            case 4://小程序
                $data = [
                    'touser' => $fromUsername,
                    'msgtype' => 'miniprogrampage',
                    'miniprogrampage' => [
                        'title' => '准了APP',
                        'pagepath' => 'pages/index/index',//小程序的页面路径，跟app.json对齐，支持参数，比如pages/index/index?foo=bar
                        'thumb_media_id' => ''//缩略图/小程序卡片图片的媒体ID，小程序卡片图片建议大小为520*416
                    ]
                ];
                break;
            default:
                $content = '您好，有什么能帮助你?';
                $data = [
                    'touser' => $fromUsername,
                    'msgtype' => 'text',
                    'text' => [
                        'content' => $content
                    ]
                ];
                break;
        }
        $json = json_encode($data, JSON_UNESCAPED_UNICODE);
        //获取token
        $access_token = $this->get_accessToken();
        /*
         * POST发送https请求客服接口api
         */
        $url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
        //以'json'格式发送post的https请求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!empty($json))
        {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);
        //若请求失败记录日志
        if (curl_errno($curl))
        {
            Log::write('Errno' . curl_error($curl), 'error', true);
        }
        curl_close($curl);
        if ($output == 0)
        {
            return 'success';
        }
        throw new ApiException($output);
    }


    /**
     * 调用微信api，获取access_token，有效期7200s -xzz0704
     * @return mixed|string
     */
    public function get_accessToken()
    {
        $token = Cache::get('mini_customer_access_token');
        /* 在有效期，直接返回access_token */
        if ($token)
        {
            return $token;
        }
        /* 不在有效期，重新发送请求，获取access_token */
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $this->app_id . '&secret=' . $this->app_secret;
        $result = Util::curl_get($url);
        $res = json_decode($result, true);   //json字符串转数组

        if ($res)
        {
            Cache::set('mini_customer_access_token', $res['access_token'], 7100);
            return $res['access_token'];
        }
        return 'api return error';
    }
}